<template>
  <div>
    <BasicModal
      @register="register"
      :title="title"
      width="600px"
      :destroyOnClose="true"
      :canFullscreen="false"
      :showOkBtn="false"
      :showCancelBtn="false"
    >
      <BasicForm @register="registerForm">
        <template #num>
          <span>{{ checkedRows.length }}个</span>
          <Button type="link" size="small" @click="handleOpenInstitution">查看</Button>
        </template>
      </BasicForm>
    </BasicModal>
    <InstitutionModal @register="registerInstitution" />
    <PublishError @register="registerPublishError" />
  </div>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { Button } from '@/components/Button';
  import InstitutionModal from './institutionModal.vue';
  import PublishError from '../../components/publishError.vue';
  import { useModal } from '@/components/Modal';
  import { ref } from 'vue';
  import { publishExp, submitAudit, templateList } from '@/api/version';
  import { useMessage } from '@/hooks/web/useMessage';
  import { IErrMsg, ITemplateListResult, IVersionPageListResult } from '@/api/version/type';

  const title = ref('发布体验版');
  const type = ref(1);
  const { createMessage } = useMessage();
  const templateId = ref(0);
  const checkedRows = ref<IVersionPageListResult[]>([]);

  const emit = defineEmits(['reload']);

  interface formData {
    userVersion: string;
    userDesc: string;
    templateId: number;
    tenantIds: number[];
  }

  const form = ref<formData>({
    userVersion: '',
    userDesc: '',
    templateId: 0,
    tenantIds: [],
  });

  const baseSchemas: FormSchema[] = [
    {
      field: 'templateType',
      component: 'RadioGroup',
      label: '模板库',
      defaultValue: 0,
      componentProps: {
        options: [
          {
            label: '标准模板库',
            value: 1,
            key: '1',
          },
          {
            label: '普通模板库',
            value: 0,
            key: '0',
          },
        ],
        onChange: async (e) => {
          templateId.value = e.target.value;
          form.value.userVersion = '';

          setFieldsValue({
            templateId: '',
          });

          setFieldsValue({
            userDesc: '',
          });

          let options: ITemplateListResult[] = await templateList({
            templateType: templateId.value,
          });
          updateSchema({
            field: 'templateId',
            componentProps: {
              options: options.map((op) => {
                return {
                  label: op.user_version,
                  value: op.template_id,
                  key: op.template_id,
                  user_desc: op.user_desc,
                };
              }),
            },
          });
        },
      },
    },
    {
      field: 'templateId',
      component: 'Select',
      label: '发布版本',
    },
    {
      field: 'userDesc',
      component: 'InputTextArea',
      label: '提交说明',
      componentProps: {
        rows: 4,
      },
    },
    {
      field: 'publishType',
      component: 'RadioGroup',
      label: '发布操作',
      defaultValue: 1,
      componentProps: {
        options: [
          {
            label: '发布体验',
            value: 1,
            key: 1,
          },
          {
            label: '发布体验&提审',
            value: 2,
            key: 2,
          },
        ],
      },
    },
  ];

  const [registerForm, { validate, appendSchemaByField, setProps, updateSchema, setFieldsValue }] =
    useForm({
      schemas: [],
      autoFocusFirstItem: true,
      actionColOptions: {
        span: 24,
      },
      labelWidth: 120,
      baseColProps: { span: 18 },
      submitButtonOptions: {
        text: '确认',
      },
      resetButtonOptions: {
        text: '取消',
      },
      submitFunc: async () => {
        const data = await validate();
        console.log(data);
        setProps({
          submitButtonOptions: {
            loading: true,
          },
        });
        console.log(data, form.value);
        try {
          let params = {
            userVersion: form.value.userVersion,
            userDesc: data.userDesc,
            templateId: data.templateId,
            tenantIds: form.value.tenantIds,
          };
          let res: IErrMsg[] = await publishExp({ ...params });
          console.log('res--->', res);
          setProps({
            submitButtonOptions: {
              loading: false,
            },
          });
          if (res && res.length) {
            return openPublishErrorModal(true, {
              list: res,
            });
          }
          if (data.publishType === 2) {
            let res2: IErrMsg[] = await submitAudit({ ...params });
            if (res2 && res2.length) {
              return openPublishErrorModal(true, {
                list: res2,
              });
            }
          }

          createMessage.success('提交成功！');
          emit('reload');
          closeModal();
        } catch (error) {
          console.log('error--->', error);
          setProps({
            submitButtonOptions: {
              loading: false,
            },
          });
        }
      },
      resetFunc: async () => {
        closeModal();
      },
    });

  const [register, { closeModal }] = useModalInner(async (data) => {
    // console.log('data--->', data);
    type.value = data.type;
    let row = data.row;

    title.value = (data.type === 2 ? '批量' : '') + '发布体验版';

    let schemas: FormSchema[] = [];
    if (data.type === 1) {
      form.value.tenantIds = [data.row.tenantId] as any;
      schemas = [
        {
          field: 'organizationName',
          component: 'Input',
          label: '机构名称',
          componentProps: { disabled: true },
          defaultValue: row.organizationName,
        },
        {
          field: 'wechatAppName',
          component: 'Input',
          label: '小程序名称',
          componentProps: { disabled: true },
          defaultValue: row.wechatAppName,
        },
        {
          field: 'expVersion',
          component: 'Input',
          label: '当前版本',
          componentProps: { disabled: true },
          defaultValue: row.expVersion,
        },
        ...baseSchemas,
      ];
    } else {
      checkedRows.value = row;
      form.value.tenantIds = checkedRows.value.map((v) => v.tenantId);
      schemas = [
        { field: 'num', component: 'Input', label: '机构数量', slot: 'num' },
        ...baseSchemas,
      ];
    }

    for (let index = 0; index < schemas.length; index++) {
      const item = schemas[index];
      if (item.field === 'templateId') {
        let options: ITemplateListResult[] = await templateList({
          templateType: templateId.value,
        });
        appendSchemaByField(
          {
            ...item,
            componentProps: {
              options: options.map((op) => {
                return {
                  label: op.user_version,
                  value: op.template_id,
                  key: op.template_id,
                  user_desc: op.user_desc,
                };
              }),
              onChange: (e, v) => {
                console.log(e, v);
                form.value.userVersion = v.label;
                setFieldsValue({
                  userDesc: v.user_desc,
                });
              },
            },
          },
          '',
        );
      } else {
        appendSchemaByField(
          {
            ...item,
          },
          '',
        );
      }
    }
    // schemas.forEach((item) => {

    // });
  });

  const [registerInstitution, { openModal }] = useModal();
  const [registerPublishError, { openModal: openPublishErrorModal }] = useModal();

  function handleOpenInstitution() {
    openModal(true, {
      list: checkedRows.value.map((v) => v.organizationName),
    });
  }
</script>

<style lang="less" scoped></style>
